package com.itcp.itelpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcp.itelpicture.annotation.AuthCheck;
import com.itcp.itelpicture.common.BaseResponse;
import com.itcp.itelpicture.common.DeleteRequest;
import com.itcp.itelpicture.common.Result;
import com.itcp.itelpicture.constants.UserConstant;
import com.itcp.itelpicture.domain.dto.community.CommunityPostAddRequest;
import com.itcp.itelpicture.domain.dto.community.CommunityPostEditRequest;
import com.itcp.itelpicture.domain.dto.community.CommunityPostQueryRequest;
import com.itcp.itelpicture.domain.dto.picture.PictureUploadRequest;
import com.itcp.itelpicture.domain.po.community.CommunityPost;
import com.itcp.itelpicture.domain.po.User;
import com.itcp.itelpicture.domain.vo.PictureVO;
import com.itcp.itelpicture.domain.vo.communityVo.CommunityPostVO;
import com.itcp.itelpicture.exception.BusinessException;
import com.itcp.itelpicture.exception.ErrorCode;
import com.itcp.itelpicture.exception.ThrowUtils;
import com.itcp.itelpicture.service.ICommunityPostService;
import com.itcp.itelpicture.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 社区文章接口
 * 
 * @author wgzzz
 */
@RestController
@RequestMapping("/community/post")
@Slf4j
public class CommunityPostController {

    @Resource
    private ICommunityPostService communityPostService;

    @Resource
    private IUserService userService;

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/uploadPicture")
    public BaseResponse<String> uploadPostPicture(
            @RequestPart("file") MultipartFile multipartFile,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String imageUrl = communityPostService.uploadPicture(multipartFile, loginUser);
        return Result.success(imageUrl);
    }

    /**
     * 创建
     * 
     * @param communityPostAddRequest 创建请求
     * @param request                 HTTP请求
     * @return 文章ID
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCommunityPost(@RequestBody CommunityPostAddRequest communityPostAddRequest,
            HttpServletRequest request) {
        if (communityPostAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long result = communityPostService.addCommunityPost(communityPostAddRequest, loginUser);
        return Result.success(result);
    }

    /**
     * 删除
     * 
     * @param deleteRequest 删除请求
     * @param request       HTTP请求
     * @return 是否成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCommunityPost(@RequestBody DeleteRequest deleteRequest,
            HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = communityPostService.deleteCommunityPost(deleteRequest.getId(), loginUser);
        return Result.success(result);
    }

    /**
     * 更新（仅管理员和作者）
     * 
     * @param communityPostEditRequest 更新请求
     * @param request                  HTTP请求
     * @return 是否成功
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateCommunityPost(@RequestBody CommunityPostEditRequest communityPostEditRequest,
            HttpServletRequest request) {
        if (communityPostEditRequest == null || communityPostEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = communityPostService.updateCommunityPost(communityPostEditRequest, loginUser);
        return Result.success(result);
    }

    /**
     * 根据 id 获取文章（仅管理员可用）
     * 
     * @param id 文章ID
     * @return 文章详情
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<CommunityPost> getCommunityPostById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        CommunityPost communityPost = communityPostService.getById(id);
        ThrowUtils.throwIf(communityPost == null, ErrorCode.NOT_FOUND_ERROR);
        return Result.success(communityPost);
    }

    /**
     * 根据 id 获取包装类
     * 
     * @param id    文章ID
     * @return 文章视图
     */
    @GetMapping("/get/vo")
    public BaseResponse<CommunityPostVO> getCommunityPostVOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        CommunityPost communityPost = communityPostService.getById(id);
        ThrowUtils.throwIf(communityPost == null, ErrorCode.NOT_FOUND_ERROR);
        return Result.success(communityPostService.getCommunityPostVO(communityPost));
    }

    /**
     * 分页获取列表（仅管理员可用）
     * 
     * @param communityPostQueryRequest 查询条件
     * @return 分页结果
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<CommunityPost>> listCommunityPostByPage(
            @RequestBody CommunityPostQueryRequest communityPostQueryRequest) {
        long current = communityPostQueryRequest.getCurrent();
        long size = communityPostQueryRequest.getPageSize();
        Page<CommunityPost> communityPostPage = communityPostService.page(new Page<>(current, size),
                communityPostService.getQueryWrapper(communityPostQueryRequest));
        return Result.success(communityPostPage);
    }

    /**
     * 分页获取列表（封装类）
     * 
     * @param communityPostQueryRequest 查询条件
     * @param request                   HTTP请求
     * @return 分页结果
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CommunityPostVO>> listCommunityPostVOByPage(
            @RequestBody CommunityPostQueryRequest communityPostQueryRequest,
            HttpServletRequest request) {
        if (communityPostQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<CommunityPostVO> communityPostVOPage = communityPostService
                .listCommunityPostVOByPage(communityPostQueryRequest, request);
        return Result.success(communityPostVOPage);
    }

    /**
     * 收藏
     * 
     * @param id      文章ID
     * @param request HTTP请求
     * @return 是否成功
     */
    @PostMapping("/favorite")
    public BaseResponse<Boolean> favoriteCommunityPost(Long id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = communityPostService.favoriteCommunityPost(id, loginUser);
        return Result.success(result);
    }

    /**
     * 取消收藏
     * 
     * @param id      文章ID
     * @param request HTTP请求
     * @return 是否成功
     */
    @PostMapping("/unfavorite")
    public BaseResponse<Boolean> unfavoriteCommunityPost(Long id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = communityPostService.unfavoriteCommunityPost(id, loginUser);
        return Result.success(result);
    }
}